package com.itheima.web;

import com.itheima.domain.Student;
import com.itheima.servlet.StudentServlet;
import com.itheima.servlet.StudentServletImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        //2.封装对象
        Student student = new Student();
        try {
            BeanUtils.populate(student,parameterMap);
            //3.调用service
            StudentServlet studentService = new StudentServletImpl();
            boolean add = studentService.add(student);
            //4.响应
            if(add) {
                //重定向到查询所有的Servlet
                response.sendRedirect("ListServlet");
//                request.getRequestDispatcher("/listServlet").forward(request,response);
            }else{
                response.getWriter().write("添加失败,三秒后跳转");
                response.setHeader("Refresh","3;url=ListServlet");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
